﻿#include "storage/StoragePreferences.h"
#include <sys/timeb.h>
#include "context.h"
#include "uart/ProtocolParser.h"
#include "uart/ProtocolCustom.h"
#include <base/handler.hpp>
#include <base/strings.hpp>
#include <base/timer.hpp>

#define TIME_DAY(n) (n * 24 * 60 * 60) //n天的秒数

#define CUR_CARTRIDGE_TYPE_KEY "cur_cartridge_type"

#define CARTRIDGE_TOTAL_WATER_KEY "cartridge_total_water"

typedef struct {
    const char* cartridge_power_on_time_key;
    const char* cartridge_water_volume_key;
    int power_on_time_life_max;          //通电寿命最大值
    int water_volume_life_max;          //制水量寿命最大值
    int power_on_time_start;     //通电时间开始
    int water_volume_start;      //制水量开始
    int life_power_on;           //通电寿命(0-100)
    int life_water_volume;       //制水量寿命(0-100)
    int reset_power_on_time;     //重置通电时间
    int reset_water_volume;      //重置制水量
} SCartridgeLife;

namespace water {

static void _on_message_handler(const base::message<void*> *msg, const void *user_data);
static base::handler<void *> _s_timer_handler(_on_message_handler, NULL);

static SCartridgeLife _cartridge_life[E_CARTRIDGE_TYPE_ALL] = {
    { "cartridge_ppc_power_on_time", "cartridge_ppc_water_volume", (TIME_DAY(365)) , (2000 * 1000) , 0, 0, 0, 0, 0, 0 },
    { "cartridge_ro_power_on_time", "cartridge_ro_water_volume", (TIME_DAY(730)) , (4000 * 1000), 0, 0, 0, 0, 0, 0 },
    { "cartridge_c2_power_on_time", "cartridge_c2_water_volume", (TIME_DAY(548)), (3000 * 1000), 0, 0, 0, 0, 0, 0 },
};

//快检数据
static SCartridgeLife _cartridge_fast_life[E_CARTRIDGE_TYPE_ALL] = {
    { "", "", 365, 5000, 0, 0, 0, 0, 0, 0 },
    { "", "", 730, 10000, 0, 0, 0, 0, 0, 0  },
    { "", "", 548, 7500, 0, 0, 0, 0, 0, 0  },
};

static int _power_on_time = 0;
static int _water_volume = 0;

//增压泵工作时间(s)
static int64_t _air_pump_work_time;

static bool _is_air_pump_work = false;

static int64_t _last_air_pump_work_time;

static bool _is_fast_check = false;

//流量计流量记录
static int _flowmeter_record = 0;

//static int last_flowmeter_data = 0;

//热水记录
static int _hot_water_record = 0;

//static int last_hot_water_data = 0;

//重置过滤器总水量记录
static int _reset_total_water = 0;
//开始过滤器总水量记录
static int _start_total_water = 0;

static void _send_timer_message() {
    _s_timer_handler.send_message_delayed(0, 1000);
}

//static void _remove_timer_message() {
//	_s_timer_handler.remove_messages(0);
//}

static SCartridgeLife& get_cartridge_life_s(E_CARTRIDGE_TYPE type) {
    if(_is_fast_check) {
        return _cartridge_fast_life[type];
    }else {
        return _cartridge_life[type];
    }
}

//获取从上电开始累计的过滤水量
int get_total_cartridge_water_all() {
     //过滤水量 = 流量计1 + 增压泵工作时间 * 1.3L/分钟
    int total_water = 0;
    total_water = _air_pump_work_time / 60.0 * 1300 + _flowmeter_record + _hot_water_record;
    return total_water;
}

//获取总过滤水量(滤芯寿命)
static int get_total_cartridge_water_life(E_CARTRIDGE_TYPE type) {
    if(type != E_CARTRIDGE_TYPE_ALL) {
        _water_volume = get_total_cartridge_water_all();
//        LOGD("get_total_cartridge_water: %d, get_cartridge_life_s(type).water_volume_start: %d\n", _water_volume, get_cartridge_life_s(type).water_volume_start);
        return get_cartridge_life_s(type).water_volume_start + _water_volume - get_cartridge_life_s(type).reset_water_volume;
    }
    return 0;
}

void cartridge_life_init() {
    _send_timer_message();  //启动定时器
    for(int i = 0; i < E_CARTRIDGE_TYPE_ALL; i++) {
        _cartridge_life[i].power_on_time_start = StoragePreferences::getInt(_cartridge_life[i].cartridge_power_on_time_key, 0);
        _cartridge_life[i].water_volume_start = StoragePreferences::getInt(_cartridge_life[i].cartridge_water_volume_key, 0);
        _cartridge_life[i].reset_power_on_time = 0;
        _cartridge_life[i].reset_water_volume = 0;
    }
    _start_total_water = StoragePreferences::getInt(CARTRIDGE_TOTAL_WATER_KEY, 0);
    init_tds();
}

void cartridge_data_save() {
	E_CARTRIDGE_TYPE type = E_CARTRIDGE_TYPE_ALL;
    
    StoragePreferences::putInt(CARTRIDGE_TOTAL_WATER_KEY, _start_total_water + get_total_cartridge_water_all() - _reset_total_water);
    LOGD("save total_water: %d\n", StoragePreferences::getInt(CARTRIDGE_TOTAL_WATER_KEY, 0));

    save_tds();

	if(type == E_CARTRIDGE_TYPE_ALL) {
		LOGD("save!!\n");
		for(int i = 0; i < E_CARTRIDGE_TYPE_ALL; i++) {
			StoragePreferences::putInt(_cartridge_life[i].cartridge_power_on_time_key, _cartridge_life[i].power_on_time_start + _power_on_time - _cartridge_life[i].reset_power_on_time);
			StoragePreferences::putInt(_cartridge_life[i].cartridge_water_volume_key, _cartridge_life[i].water_volume_start + get_total_cartridge_water_all() - _cartridge_life[i].reset_water_volume);
			LOGD("i: %d, save power_on_time: %d, water_volume: %d\n", i,
					StoragePreferences::getInt(_cartridge_life[i].cartridge_power_on_time_key, 0),
					StoragePreferences::getInt(_cartridge_life[i].cartridge_water_volume_key, 0));
		}
	}else {
		StoragePreferences::putInt(_cartridge_life[type].cartridge_power_on_time_key, _cartridge_life[type].power_on_time_start + _power_on_time - _cartridge_life[type].reset_power_on_time);
		StoragePreferences::putInt(_cartridge_life[type].cartridge_water_volume_key, _cartridge_life[type].water_volume_start + get_total_cartridge_water_all() - _cartridge_life[type].reset_water_volume);
	}
}

static void power_on_count() {
    _power_on_time++;   //通电时间+1s
   //开机后进入待机状态分别间隔1分钟/3分钟/8分钟各写一次,后面60分钟一次
   if(_power_on_time == 60) {
        cartridge_data_save();	//保存滤芯寿命数据相关
   }else if(_power_on_time == 240) {
        cartridge_data_save();
   }else if(_power_on_time == 720) {
        cartridge_data_save();
   }else if((_power_on_time - 720) % 3600 == 0) {
        cartridge_data_save();
   }

   //制水期间每1分钟保存一次
   static int _last_power_on_time = 0;
   if(water::get_water_state() != E_WATER_STATE_IDLE) {
        _last_power_on_time++;
        if(_last_power_on_time % 60 == 0) {
            cartridge_data_save();
        }
   }else {
        _last_power_on_time = 0;
   }
}

//static void record_flowmeter_data() {
//    if(last_flowmeter_data < getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp) {
//    	static bool is_first = true;
//    	if(!is_first) {
//    		if(water::get_water_state() != E_WATER_STATE_IDLE){
//    			_flowmeter_record += getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp - last_flowmeter_data;
//    		}
//    	}else{
//    		is_first = false;
//    	}
//
//        last_flowmeter_data = getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp;
//    } else if(last_flowmeter_data > getProtocolData().inquiry_e5_b2.hot_tank_ntc_temp) {
//        last_flowmeter_data = 0;
//    }
//    // LOGD("flowmeter_record: %d\n", _flowmeter_record);
//}
//
//static void record_hot_water_data() {
//    if(last_hot_water_data < getProtocolData().inquiry_a5.output_water_output_total) {
//    	static bool is_first = true;
//    	if(!is_first) {
//    		_hot_water_record += getProtocolData().inquiry_a5.output_water_output_total - last_hot_water_data;
//		}else{
//			is_first = false;
//		}
//        last_hot_water_data = getProtocolData().inquiry_a5.output_water_output_total;
//    } else if(last_hot_water_data > getProtocolData().inquiry_a5.output_water_output_total) {
//    	last_hot_water_data = getProtocolData().inquiry_a5.output_water_output_total;
//    }
//    // LOGD("_hot_water_record: %d\n", _hot_water_record);
//}

static void _on_message_handler(const base::message<void*> *msg, const void *user_data) {
    power_on_count();
    if(water::is_timer_event_running(E_TIMER_EVENT_MAKE_WATER_TIMEOUT) && water::get_water_state() == E_WATER_STATE_IDLE){
    	air_pump_work_count(protocol::getLoadSwitch(E_DEV_LOAD_TYPE_AIR_PUMP));
    }else {
    	air_pump_work_count(false);
    }
    // record_flowmeter_data();
    // record_hot_water_data();


	_send_timer_message();  
}

void air_pump_work_count(bool is_air_pump_work) {
    if(is_air_pump_work){
        if(!_is_air_pump_work) {
            _is_air_pump_work = true;

            _last_air_pump_work_time = base::uptime();
        }else {
            int64_t currentTime =  base::uptime();

            _air_pump_work_time +=  (currentTime - _last_air_pump_work_time) / 1000;
            _last_air_pump_work_time = currentTime;
        }
    } else {
        if(_is_air_pump_work) {
            _is_air_pump_work = false;
            int64_t currentTime = base::uptime();
            _air_pump_work_time +=  (currentTime - _last_air_pump_work_time) / 1000;
        }
        _last_air_pump_work_time = base::uptime();
    }
}

//通电时间寿命
static int FilterLifePowerOn(SCartridgeLife cartridge_life) {
    int life = 0;
    int power_on_time = cartridge_life.power_on_time_start + _power_on_time - cartridge_life.reset_power_on_time;
    
    if(power_on_time > cartridge_life.power_on_time_life_max) {
        life = 0;
    }else {
        life = 1.0 * (cartridge_life.power_on_time_life_max - power_on_time) / cartridge_life.power_on_time_life_max * 100;
        if(life < 100) {
            life += 1;
        }
    }
    return life;
}

//制水量寿命
static int FilterLifeWaterVolume(SCartridgeLife cartridge_life) {
    int life = 0;
    //过滤水量 = 流量计1 + 增压泵工作时间 * 1.3L/分钟
    _water_volume = get_total_cartridge_water_all();
    
    int water_volume = cartridge_life.water_volume_start + _water_volume - cartridge_life.reset_water_volume;
    
    if(water_volume > cartridge_life.water_volume_life_max) {
        life = 0;
    }else {
        life = 1.0 * (cartridge_life.water_volume_life_max - water_volume) / cartridge_life.water_volume_life_max * 100;
        if(life < 100) {
            life += 1;
        }
    }
    return life;
}

int get_cartridge_life(E_CARTRIDGE_TYPE type) {
    if(type != E_CARTRIDGE_TYPE_ALL) {
        get_cartridge_life_s(type).life_water_volume = FilterLifeWaterVolume(get_cartridge_life_s(type));
        get_cartridge_life_s(type).life_power_on = FilterLifePowerOn(get_cartridge_life_s(type));
        return (get_cartridge_life_s(type).life_water_volume < get_cartridge_life_s(type).life_power_on ? get_cartridge_life_s(type).life_water_volume : get_cartridge_life_s(type).life_power_on);
    }
    return 0;
}

void reset_cartridge(E_CARTRIDGE_TYPE type) {
	if(!_is_fast_check) {
		 if(type != E_CARTRIDGE_TYPE_ALL) {
			_cartridge_life[type].reset_power_on_time = _power_on_time;
			_cartridge_life[type].reset_water_volume = get_total_cartridge_water_all();
	//        LOGD("reset_cartridge: %d\n", _cartridge_life[type].reset_water_volume);

			StoragePreferences::putInt(_cartridge_life[type].cartridge_power_on_time_key, 0);
			StoragePreferences::putInt(_cartridge_life[type].cartridge_water_volume_key, 0);
			_cartridge_life[type].power_on_time_start = 0;
			_cartridge_life[type].water_volume_start = 0;
		} else {
			for(int i = 0; i < E_CARTRIDGE_TYPE_ALL; i++) {
				_cartridge_life[i].reset_power_on_time = _power_on_time;

				_cartridge_life[i].reset_water_volume = get_total_cartridge_water_all();
	//            LOGD("reset_cartridge: %d\n", _cartridge_life[i].reset_water_volume);
				StoragePreferences::putInt(_cartridge_life[i].cartridge_power_on_time_key, 0);
				StoragePreferences::putInt(_cartridge_life[i].cartridge_water_volume_key, 0);
				_cartridge_life[i].power_on_time_start = 0;
				_cartridge_life[i].water_volume_start = 0;
			}
		}
	}else {
		if(type != E_CARTRIDGE_TYPE_ALL) {
			_cartridge_fast_life[type].reset_power_on_time = _power_on_time;
			_cartridge_fast_life[type].reset_water_volume = get_total_cartridge_water_all();
			_cartridge_fast_life[type].power_on_time_start = 0;
			_cartridge_fast_life[type].water_volume_start = 0;
		} else {
			for(int i = 0; i < E_CARTRIDGE_TYPE_ALL; i++) {
				_cartridge_fast_life[i].reset_power_on_time = _power_on_time;
				_cartridge_fast_life[i].reset_water_volume = get_total_cartridge_water_all();
				_cartridge_fast_life[i].power_on_time_start = 0;
				_cartridge_fast_life[i].water_volume_start = 0;
			}
		}
	}
}

//获取总过滤水量(ml)
int get_total_cartridge_water() {
    return _start_total_water + get_total_cartridge_water_all() - _reset_total_water;
}

void reset_total_cartridge_water() {
    _start_total_water = 0;
    _reset_total_water = get_total_cartridge_water_all();
    StoragePreferences::putInt(CARTRIDGE_TOTAL_WATER_KEY, 0);
}

int get_cartridge_life_second(E_CARTRIDGE_TYPE type) {
    if(type != E_CARTRIDGE_TYPE_ALL) {
        int power_on_time = get_cartridge_life_s(type).power_on_time_start + _power_on_time - get_cartridge_life_s(type).reset_power_on_time;
        if(power_on_time > get_cartridge_life_s(type).power_on_time_life_max) {
            return 0;
        } else {
            return (get_cartridge_life_s(type).power_on_time_life_max - power_on_time);
        }
    }
    return 0;
}

int get_cartridge_life_flow(E_CARTRIDGE_TYPE type) {
    if(type != E_CARTRIDGE_TYPE_ALL) {
        int water_volume = get_total_cartridge_water_life(type);
        if(water_volume > get_cartridge_life_s(type).water_volume_life_max) {
            return 0;
        } else {
            return (get_cartridge_life_s(type).water_volume_life_max - water_volume);
        }
    }
    return 0;
}

void set_cartridge_fast_check(bool is_fast_check) {
    _is_fast_check = is_fast_check;
    for(int i = 0; i < E_CARTRIDGE_TYPE_ALL; i++) {
        if(_cartridge_fast_life[i].reset_power_on_time == 0) {    //每次上电进入才重置
            _cartridge_fast_life[i].reset_power_on_time = _power_on_time;
            _cartridge_fast_life[i].reset_water_volume = get_total_cartridge_water_all();
            _cartridge_fast_life[i].power_on_time_start = 0;
            _cartridge_fast_life[i].water_volume_start = 0;
        }
    }
}

void add_flowmeter_data(int flow_meter_data) {
    _flowmeter_record += flow_meter_data;
}

void add_hot_water_data(int hot_water_data) {
    _hot_water_record += hot_water_data;
}

}

